<?php
/********************************************************
 * Component: Common																			*
 *	Author: TuyenND																				*
 *	Date: 20-09-2007																			*
 * Note: All functions in this component can be changed	*
 * belong to each project																*
 ********************************************************/
App::uses('Component', 'Controller');
class CommonComponent extends Component  {
	public $components = array('Session');
	/**
	 * Fix SQL Injection
	 */
	public function fixSqlInjection($str){
		if(!ereg('[\\\'\"<>:;,=&]', $str)){
			mysql_escape_string($str);
			return $str;
		}else{
			return "";
		}
	}

	public function create_random_string($num){
		//Tao du lieu cho hinh ngau nhien
		$chars = array( 'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h', 'H', 'i', 'I', 'j', 'J',  'k', 'K', 'l', 'L', 'm', 'M', 'n', 'N', 'o', 'p', 'P', 'q', 'Q', 'r', 'R', 's', 'S', 't', 'T',  'u', 'U', 'v', 'V', 'w', 'W', 'x', 'X', 'y', 'Y', 'z', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9');
		$max_chars = count($chars) - 1;
		for($i = 0; $i < $num; $i++){
			$code = ( $i == 0 ) ? $chars[rand(0, $max_chars)] : $code . $chars[rand(0, $max_chars)];
		}
		return $code;
	}

	/**
	 * Creat list of call log status
	 */
public function listCountry(){
		return array(
			'ad'=>'ad',
			'ae'=>'ae',       
			'af'=>'af',
			'ag'=>'ag',
			'ai'=>'ai',
			'al'=>'al',
			'am'=>'am',
			'an'=>'an',
			'ao'=>'ao',
			'ar'=>'ar',
			'as'=>'as',
			'at'=>'at',
			'au'=>'au',
			'aw'=>'aw',
			'ax'=>'ax',
			'az'=>'az',
			'ba'=>'ba',
			'bb'=>'bb',
			'bd'=>'bd',
			'be'=>'be',
			'bf'=>'bf',
			'bg'=>'bg',
			'bh'=>'bh',
			'bi'=>'bi',
			'bj'=>'bj',
			'bm'=>'bm',
			'bn'=>'bn',
			'bo'=>'bo',
			'br'=>'br',
			'bs'=>'bs',
			'bt'=>'bt',
			'bv'=>'bv',
			'bw'=>'bw',
			'by'=>'by',
			'bz'=>'bz',
			'ca'=>'ca',
			'catalonia'=>'catalonia',
			'cc'=>'cc',
			'cd'=>'cd',
			'cf'=>'cf',
			'cg'=>'cg',
			'ch'=>'ch',
			'ci'=>'ci',
			'ck'=>'ck',
			'cl'=>'cl',
			'cm'=>'cm',
			'cn'=>'cn',
			'co'=>'co',
			'cr'=>'cr',
			'cs'=>'cs',
			'cu'=>'cu',
			'cv'=>'cv',
			'cx'=>'cx',
			'cy'=>'cy',
			'cz'=>'cz',
			'de'=>'de',
			'dj'=>'dj',
			'dk'=>'dk',
			'dm'=>'dm',
			'do'=>'do',
			'dz'=>'dz',
			'ec'=>'ec',
			'ee'=>'ee',
			'eg'=>'eg',
			'eh'=>'eh',
			'en_uk'=>'English',
			'en_us'=>'English',
			'er'=>'er',
			'es'=>'es',
			'et'=>'et',
			'fam'=>'fam',
			'fi'=>'fi',
			'fj'=>'fj',
			'fk'=>'fk',
			'fm'=>'fm',
			'fo'=>'fo',
			'fr'=>'fr',
			'ga'=>'ga',
			'gb'=>'gb',
			'gd'=>'gd',
			'ge'=>'ge',
			'gf'=>'gf',
			'gh'=>'gh',
			'gi'=>'gi',
			'gl'=>'gl',
			'gm'=>'gm',
			'gn'=>'gn',
			'gp'=>'gp',
			'gq'=>'gq',
			'gr'=>'gr',
			'gs'=>'gs',
			'gt'=>'gt',
			'gu'=>'gu',
			'gw'=>'gw',
			'gy'=>'gy',
			'hk'=>'hk',
			'hm'=>'hm',
			'hn'=>'hn',
			'hr'=>'hr',
			'ht'=>'ht',
			'hu'=>'hu',
			'id'=>'id',
			'ie'=>'ie',
			'il'=>'il',
			'in'=>'in',
			'io'=>'io',
			'iq'=>'iq',
			'ir'=>'ir',
			'is'=>'is',
			'it'=>'it',
			'jm'=>'jm',
			'jo'=>'jo',
			'jp'=>'日本語',
			'ke'=>'ke',
			'kg'=>'kg',
			'kh'=>'kh',
			'ki'=>'ki',
			'km'=>'km',
			'kn'=>'kn',
			'kp'=>'kp',
			'kr'=>'kr',
			'kw'=>'kw',
			'ky'=>'ky',
			'kz'=>'kz',
			'la'=>'la',
			'lb'=>'lb',
			'lc'=>'lc',
			'li'=>'li',
			'lk'=>'lk',
			'lr'=>'lr',
			'ls'=>'ls',
			'lt'=>'lt',
			'lu'=>'lu',
			'lv'=>'lv',
			'ly'=>'ly',
			'ma'=>'ma',
			'mc'=>'mc',
			'md'=>'md',
			'me'=>'me',
			'mg'=>'mg',
			'mh'=>'mh',
			'mk'=>'mk',
			'ml'=>'ml',
			'mm'=>'mm',
			'mn'=>'mn',
			'mo'=>'mo',
			'mp'=>'mp',
			'mq'=>'mq',
			'mr'=>'mr',
			'ms'=>'ms',
			'mt'=>'mt',
			'mu'=>'mu',
			'mv'=>'mv',
			'mw'=>'mw',
			'mx'=>'mx',
			'my'=>'my',
			'mz'=>'mz',
			'na'=>'na',
			'nc'=>'nc',
			'ne'=>'ne',
			'nf'=>'nf',
			'ng'=>'ng',
			'ni'=>'ni',
			'nl'=>'nl',
			'no'=>'no',
			'np'=>'np',
			'nr'=>'nr',
			'nu'=>'nu',
			'nz'=>'nz',
			'om'=>'om',
			'pa'=>'pa',
			'pe'=>'pe',
			'pf'=>'pf',
			'pg'=>'pg',
			'ph'=>'ph',
			'pk'=>'pk',
			'pl'=>'pl',
			'pm'=>'pm',
			'pn'=>'pn',
			'pr'=>'pr',
			'ps'=>'ps',
			'pt'=>'pt',
			'pw'=>'pw',
			'py'=>'py',
			'qa'=>'qa',
			're'=>'re',
			'ro'=>'ro',
			'rs'=>'rs',
			'ru'=>'ru',
			'rw'=>'rw',
			'sa'=>'sa',
			'sb'=>'sb',
			'sc'=>'sc',
			'scotland'=>'scotland',
			'sd'=>'sd',
			'se'=>'se',
			'sg'=>'sg',
			'sh'=>'sh',
			'si'=>'si',
			'sj'=>'sj',
			'sk'=>'sk',
			'sl'=>'sl',
			'sm'=>'sm',
			'sn'=>'sn',
			'so'=>'so',
			'sr'=>'sr',
			'st'=>'st',
			'sv'=>'sv',
			'sy'=>'sy',
			'sz'=>'sz',
			'tc'=>'tc',
			'td'=>'td',
			'tf'=>'tf',
			'tg'=>'tg',
			'th'=>'th',
			'tj'=>'tj',
			'tk'=>'tk',
			'tl'=>'tl',
			'tm'=>'tm',
			'tn'=>'tn',
			'to'=>'to',
			'tr'=>'tr',
			'tt'=>'tt',
			'tv'=>'tv',
			'tw'=>'tw',
			'tz'=>'tz',
			'ua'=>'ua',
			'ug'=>'ug',
			'um'=>'um',
			'us'=>'English',
			'uy'=>'uy',
			'uz'=>'uz',
			'va'=>'va',
			'vc'=>'vc',
			've'=>'ve',
			'vg'=>'vg',
			'vi'=>'vi',
			'vie'=>'Tiếng Việt',
			'vu'=>'vu',
			'wales'=>'wales',
			'wf'=>'wf',
			'ws'=>'ws',
			'ye'=>'ye',
			'yt'=>'yt',
			'za'=>'za',
			'zm'=>'zm',
			'zw'=>'zw',
		);
	
	}



	//xac dinh cac method khong can check
	public function baseMethod(){
		return array('admin_page',
					'admin_sort',
					'admin_filter',
					'admin_display',
					'admin_changeLocale',
					'admin_logout',
	'beforeRender',
    'beforeFilter',
	'initAuth',
	'checkAcl',
	'throwErrorMessage',
	'redirectAjaxTo',
		'redirectTo',
	'appError',
	'__construct',
	'__isset',
	'__get',
	'__set',
	'setRequest',
	'invokeAction',
	'_isPrivateAction',
	'_getScaffold',
	'_mergeControllerVars',
	'_mergeUses',
	'implementedEvents',
	'constructClasses',
	'getEventManager',
	'startupProcess',
	'shutdownProcess',
	'httpCodes',
	'loadModel',
	'redirect',
	'_parseBeforeRedirect',
	'header',
	'set',
	'setAction',
	'validate',
	'validateErrors',
	'render',
	'referer',
	'disableCache',
	'flash',
	'postConditions',
	'paginate',
	'beforeRedirect',
	'afterFilter',
	'beforeScaffold',
	'_beforeScaffold',
	'afterScaffoldSave',
	'_afterScaffoldSave',
	'afterScaffoldSaveError',
	'_afterScaffoldSaveError',
	'scaffoldError',
	'_scaffoldError',
	'toString',
	'requestAction',
	'dispatchMethod',
	'_stop',
	'log',
	'_set',
	'_mergeVars',
	'updateSeoLink'
					
		
	);
	}

	//xac dinh cac Controller khong can check
	public function baseController(){
		return array('Permissions',
					'App',
					'Errors',
					'Pages'
					);
	}

	//xac dinh cac method khong can check
	public function baseMethodController(){
		return array('Homes/admin_index',
		'Menus/admin_getMenu',
		'Users/admin_login',
		'Users/admin_logout',
		);
	}

	//same permission
	//return the main permission
	public function samePermission($permission){
		//value la gia tri chinh cua aco( dc luu vao db)
		$rt=$permission;
		$same= array(
			'controllers/Menus/admin_moveUp'=>'controllers/Menus/admin_edit',
			'controllers/Menus/admin_moveDown'=>'controllers/Menus/admin_edit',
			'controllers/Modules/admin_moveUp'=>'controllers/Modules/admin_edit',
			'controllers/Modules/admin_moveDown'=>'controllers/Modules/admin_edit',
			'controllers/Menus/admin_getMethodList'=>'controllers/Menus/admin_list',
			'controllers/Menus/admin_getControllerList'=>'controllers/Menus/admin_list',
		);
		if(isset($same[$permission]))$rt=$same[$permission];

		//method for all controller
		$method=substr($permission,strrpos($permission,'/')+1);
		$sameMethod= array(
			'admin_index'=>'admin_lists',
			'admin_selCat'=>'admin_lists',
			'admin_save'=>'admin_edit',
			'getLangs'=>'admin_lists',
			'admin_getList'=>'admin_lists',
		);
		//t(substr($permission,0,strrpos($permission,'/')+1).$sameMethod[$method]);
		if(isset($sameMethod[$method]))$rt=substr($permission,0,strrpos($permission,'/')+1).$sameMethod[$method];
		return $rt;
	}

	//check if is system public function
	public function isSystemModule($controller=null){
		//value la gia tri chinh cua aco( dc luu vao db)
		$rt=false;
		$arrController= array(
			'Configs',
			'Acos',
			'Tools',
			'Menus',
			
			'Groups',
			'Resources',
			'ResourceCategories'
			);
			if(in_array($controller,$arrController))$rt=true;
			return $rt;
	}

	public function getSecImage($isRefresh=0){
		//t(WWW_ROOT.'files/ARIAL.TTF');
		if($this->Session->check('Captcha') && !$isRefresh){
			return $this->Session->read('Captcha');
		}
		else{
			$captcha=$this->Common->create_random_string(4);
			$this->Session->write('Captcha',$captcha);
			$this->Common->ScImage2($captcha,'ARIALBD.TTF',90,20);
		}
		$this->autoRender=false;
	}

	public function ScImage($str,$fontfile,$width,$height) {
		putenv('GDFONTPATH=' . realpath('.'));
		//create the image
		$w=$width;
		$h=$height;
		$f='arial.ttf';//$this->webroot.'files/ARIAL.TTF';
		$captcha=$str;
		$image = @imagecreate($w, $h)
		or die('Cannot create main image!');

		# Set the background and the text color of the CAPTCHA image using the imagecolorallocate PHP function:

		// set the captcha image  -  text will be white rendered on black
		$bg_color = imagecolorallocate($image, 255, 255, 255);
		//we don't random here to be sure that the text is visible
		$captcha_color = imagecolorallocate($image, 255, 255, 255);
		//we don't random here to be sure that the text is visible

		# The resulting CAPTCHA image will include some generated lines, dots, and rectangles. But before that, you generate random colors for it, using the imagecolorallocate function:

		//backstage colors  -  lines, dots and rectangles
		$line_color = imagecolorallocate($image, mt_rand(0,255), 0, 255);
		$dots_color = imagecolorallocate($image, mt_rand(0,255),255,mt_rand(0,255));
		$rect_color = imagecolorallocate($image, 0,mt_rand(50,127),50);

		# Add some "security" marks. For this, you will draw with random colors some dots, rectangles, and lines in the background of the CAPTCHA to make sure that a robot application can not identify and extract the CAPTCHA text (in addition, the text is rendered with different sizes and fonts, and at different coordinates). To generate random dots for the background of the CAPTCHA image, you use the imagefilledellipse PHP function with random x and y coordinates for the center, width, and height. The x coordinate of the center will be a number between 0 and the width of the ellipse; the y coordinate of the center is a number between 0 and the height of the ellipse. The width and height of the ellipse are random numbers between 0 and 3, for obtaining ellipses with dot aspect.

		// generate random dots
		for( $i=0; $i<($w * $h); $i++ ) {
			imagefilledellipse($image, mt_rand(0,$w), mt_rand(0,$h), mt_rand(0,3),
			mt_rand(0,3), $dots_color);
		}

		#To generate random lines using the imageline PHP function, randomly generate the lengths and the coordinates of the lines as in the below code:

		// generate random lines
		for( $i=0; $i<($w + $h)/3; $i++ ) {
			imageline($image, mt_rand(0,$w), mt_rand(0,$h), mt_rand(0,$w),
			mt_rand(0,$h), $line_color);
		}

		#To generate random rectangles using the imagerectangle PHP function, randomly generate the sizes of the rectangles as in the below code:

		// generate random rectangles
		for( $i=0; $i<($w + $h)/3; $i++ ) {
			imagerectangle($image, mt_rand(0,$w), mt_rand(0,$h), mt_rand(0,$w),
			mt_rand(0,$h), $rect_color);
		}

		# Create a bounding box of text using TrueType fonts. To do that, you can use the imagettfbbox PHP function:

		// create bounding box in pixels for a TrueType text
		$tb = imagettfbbox($h * 0.80, 0, $f, $captcha)
		or die('Cannot create bounding box in pixels for this TrueType text!');

		# The most important step is writing the generated text on top of the generated image using the TrueType font. For this, you need the imagettftext PHP function.

		$urcX = ($w - $tb[4])/2; //tb[4] = upper right corner, X position
		$urcY = ($h - $tb[5])/2; //tb[5] = upper right corner, Y position
		//write the given text  into the image using TrueType font
		imagettftext($image, $h * 0.80, 0, $urcX, $urcY, $captcha_color, $f , $captcha)
		or die('Cannot write the given text  into the image using TrueType font!');

		# For a nice design, you can go further and apply image filters. For example, you can apply IMG_FILTER_NEGATE and IMG_FILTER_SMOOTH PHP predefined image filters using the imagefilter PHP function:

		//apply two image filters
		imagefilter($image,IMG_FILTER_NEGATE);
		imagefilter($image,IMG_FILTER_SMOOTH,1);

		# Output the CAPTCHA image on the browser:

		// output captcha image to browser
		header('Content-Type: image/jpeg');
		imagejpeg($image);

		imagedestroy($image);
			
	}

	public function ScImage2($str,$fontfile,$width,$height) {
		$code = $str;
		/* font size will be 75% of the image height */
		$font=$fontfile;
		$font_size = $height * 0.75;
		$image = imagecreate($width, $height) or die('Cannot initialize new GD image stream');
		/* set the colours */
		$background_color = imagecolorallocate($image, 255, 255, 255);
		$text_color = imagecolorallocate($image, 20, 40, 100);
		$noise_color = imagecolorallocate($image, 100, 120, 180);
		/* generate random dots in background */
		for( $i=0; $i<($width*$height)/3; $i++ ) {
			imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
		}
		/* generate random lines in background */
		for( $i=0; $i<($width*$height)/150; $i++ ) {
			imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
		}
		/* create textbox and add text */
		$textbox = imagettfbbox($font_size, 0, $font, $code) or die('Error in imagettfbbox function');
		$x = ($width - $textbox[4])/2;
		$y = ($height - $textbox[5])/2;
		imagettftext($image, $font_size, 0, $x, $y, $text_color, $font , $code) or die('Error in imagettftext function');
		/* output captcha image to browser */
		header('Content-Type: image/jpeg');
		imagejpeg($image);
		imagedestroy($image);
		$_SESSION['security_code'] = $code;
			
	}

	public function createWebRootFolder($path){
		$lsPath=explode('/', $path);
		$strPath=WWW_ROOT;
		foreach($lsPath as $k=>$v){
			$strPath.='/'.$v;
			if(!is_dir($strPath))mkdir($strPath,0777);
		}

	}
	
	public function replaceUnicodeChar($text="",$special="-"){
		$finds=array('á','à','ả','ã','ạ','ă','ắ','ằ','ẳ','ẵ','ặ','â','ấ','ầ','ẩ','ẫ','ậ');
		$text=str_replace($finds, 'a', $text);
		$finds=array('Á','À','Ả','Ã','Ạ','Ă','Ắ','Ằ','Ẳ','Ẵ','Ặ','Â','Ấ','Ầ','Ẩ','Ẫ','Ậ');
		$text=str_replace($finds, 'A', $text);
		$finds=array('ó','ò','ỏ','õ','ọ','ơ','ớ','ờ','ở','ỡ','ợ','ô','ố','ồ','ổ','ỗ','ộ');
		$text=str_replace($finds, 'o', $text);
		$finds=array('Ó','Ò','Ỏ','Õ','Ọ','Ơ','Ớ','Ờ','Ở','Ỡ','Ợ','Ô','Ố','Ồ','Ổ','Ỗ','Ộ');
		$text=str_replace($finds, 'O', $text);		
		$finds=array('é','è','ẻ','ẽ','ẹ','ê','ế','ề','ể','ễ','ệ');		
		$text=str_replace($finds, 'e', $text);
		$finds=array('É','È','Ẻ','Ẽ','Ẹ','Ê','Ế','Ề','Ể','Ễ','Ệ');		
		$text=str_replace($finds, 'E', $text);
		$finds=array('ú','ù','ủ','ũ','ụ','ư','ứ','ừ','ử','ữ','ự');		
		$text=str_replace($finds, 'u', $text);
		$finds=array('Ú','Ù','Ủ','Ũ','Ụ','Ư','Ứ','Ừ','Ử','Ữ','Ự');		
		$text=str_replace($finds, 'U', $text);
		$finds=array('í','ì','ỉ','ĩ','ị');		
		$text=str_replace($finds, 'i', $text);
		$finds=array('Í','Ì','Ỉ','Ĩ','Ị');		
		$text=str_replace($finds, 'I', $text);
		$finds=array('ý','ỳ','ỷ','ỹ','ỵ');		
		$text=str_replace($finds, 'y', $text);
		$finds=array('Ý','Ỳ','Ỷ','Ỹ','Ỵ');		
		$text=str_replace($finds, 'Y', $text);
		$finds=array('đ');		
		$text=str_replace($finds, 'd', $text);
		$finds=array('Đ');		
		$text=str_replace($finds, 'D', $text);		

		$text= preg_replace('/[^a-zA-Z0-9]/i', $special, $text);
		$text= preg_replace('/-+/i', $special, $text);
		return $text;
	
	}
	
	public function updateCacheRoute($isCheckTime=true){
		//get cache
		//check time to update -- 10s
		if(!$isCheckTime || !$this->Session->check('lastUpdatecacheurl') || time()-$this->Session->read('lastUpdatecacheurl')>Configure::read('SEOCacheRefresh'))
		{
			App::uses('FriendlyUrl', 'Model');
			$friendlyUrl=& new FriendlyUrl();
			$data=$friendlyUrl->find('list',array('fields'=>array('url','realurl')));
			//update time			
			$data['lastUpdate']=time();
			$this->Session->write('lastUpdatecacheurl',$data['lastUpdate']);
			$this->setCacheRoute($data);			
			//$friendlyUrlCache=Cache::read('friendlyUrl');
			//t($friendlyUrlCache);
		}
		
	}
	public function getCacheRoute(){
		//if debug !=0 then save in session
		if(Configure::read('debug')!=0){
    		$data=$this->Session->read('friendlyUrl');
		}
		else{
			$data=Cache::read('friendlyUrl');
		}
		if(empty($data)){
			$this->updateCacheRoute();
			return $this->getCacheRoute();
		}
		else return $data;
		//else save in cache
	}
	
	public function setCacheRoute($data=null){
		//if debug !=0 then save in session
		if(Configure::read('debug')!=0){
			//App::uses('SessionHelper', 'View/Helper');
    		//$Session=& new SessionHelper(new HelperCollection());
    		$this->Session->write('friendlyUrl',$data);
			
		}
		else{
			Cache::write('friendlyUrl',$data);
		}
		//else save in cache
	}

}


?>